var cfg = require('../../utils/cfg');
// var socketUtil = require('../../utils/socketUtil');

var app = getApp();


Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo: {},
    userAva: '',
    userText: '发起者',
    count: 0,
    timeWaitFun: {},
    roomTicket: '',
    roomMaster: '',
    masterAva: '',
    joined : false
  },

  waitUser: function () {
    let that = this;
    that.data.timeWaitFun = setInterval(function () {
      console.log('>>>>>wait...');
      let userAva = that.data.count % 2 == 0 ? '/images/defaultAva.png' : '/images/defaultAva2.png';
      let userText = that.data.count % 2 == 0 ? '等待开始...' : '等待开始.  .';
      that.data.count += 1;
      that.setData({ userAva: userAva });
      that.setData({ userText: userText });

      if (that.data.count >= 10) {
        // wx.switchTab({
        //   url: '/pages/home/home'
        // });
      }
    }, 1000);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var _self = this;
    _self.setData({
      userInfo: app.globalData.userInfo
    })

    let roomTicket = options.roomTicket;
    let roomMaster = options.openId;
    let masterAva = options.masterAva;
    console.log('>>>>>头像' + masterAva);

    _self.setData({
      userInfo: app.globalData.userInfo,
      roomTicket: roomTicket,
      roomMaster: roomMaster,
      masterAva: masterAva
    })

    wx.setStorageSync('roomTicket', options.roomTicket);

    if (roomMaster == wx.getStorageSync('loginUser').openId) {
      wx.redirectTo({
        url: '/pages/ready/ready?modelType=0',
        success: function () {
          
        },
        fail: function () {

        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this;

    if (!wx.getStorageSync('userInfo')) {
      wx.redirectTo({
        url: '/pages/welcome/welcome?fromId=1001&roomTicket=' + that.data.roomTicket + '&openId=' + that.data.roomMaster + '&masterAva=' + that.data.masterAva,
        success: function () {
          console.log('跳转到welcome页面');
        },
        fail: function () {
          console.log('跳转到welcome页面失败');
        }
      });
      return;
    }
  },

  joinRoom: function () {
    let that = this;
    if (that.data.joined) {
      wx.showToast({
        title: '已参与',
        icon: 'none',
        duration: 2000
      })

      return;
    }
    wx.request({
      url: cfg.host + cfg.mwurl.joinRoom,
      data: {
        // openId: wx.getStorageSync('loginUser').openId,
        openId: wx.getStorageSync('loginUser').openId,
        // nickName: app.globalData.userInfo.nickName,
        nickName: app.globalData.userInfo.nickName,
        // picUrl: app.globalData.userInfo.avatarUrl,
        picUrl: app.globalData.userInfo.avatarUrl,
        // roomTicket: wx.getStorageSync('roomTicket'),
        roomTicket: wx.getStorageSync('roomTicket'),
        model: 0
      },
      success: function (res) {
        console.log(res.data);

        if (res.data.code !== 1000) {

          let flag = res.data.message == '房间已过期';

          wx.showModal({
            title: '提示',
            content: res.data.message,
            showCancel : false,
            success: function (res) {
              if (res.confirm && flag) {
                wx.reLaunch({
                  url: '/pages/home/home'
                })
              } else if (res.cancel) {

              }
            }
          })
          return;
        }

        that.data.joined = true;

        that.waitUser();

        // //调转到答题页面
        // wx.reLaunch({
        //   url: '/pages/paper/paper?roomTicket=' + wx.getStorageSync('roomTicket')
        // })
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    //注册回调函数
    // socketUtil.registCallBack(this.doSocket);
    app.globalData.socketCallBack = this.doSocket;
  },

  doSocket: function (res) {

    console.log('ready socket ' + res);
    let that = this;
    let wsDTO = res

    if (1002 === wsDTO.wsType) {
      //获取答卷数据

      wx.setStorageSync('paperInfo', wsDTO);
      console.log('即将跳转页面： ');
      wx.reLaunch({
        url: '/pages/paper/paper?fromType=11&model=0'
      })
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log('ready onUnload');
   // this.leaveRoom();
    clearInterval(this.data.timeWaitFun);
  },

  leaveRoom: function () {
    let that = this;
    wx.request({
      url: cfg.host + cfg.mwurl.leaveRoom,
      data: {
        openId: wx.getStorageSync('loginUser').openId,
        roomTicket: wx.getStorageSync('roomTicket')
      },
      success: function (res) {
        console.log(res.data);
        wx.switchTab({
          url: '/pages/home/home'
        });
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: 'POST'
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})